package com.beiing.tianshuai.tianshuai.dongtai;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.adapter.DynamicRelayComment_RVAdapter;
import com.beiing.tianshuai.tianshuai.anim.LikeAnimator;
import com.beiing.tianshuai.tianshuai.app.HttpRequestConstant;
import com.beiing.tianshuai.tianshuai.base.BaseActivity;
import com.beiing.tianshuai.tianshuai.dongtai.presenter.DynamicRelayDetailPresenter;
import com.beiing.tianshuai.tianshuai.dongtai.view.DynamicDetailActivity;
import com.beiing.tianshuai.tianshuai.dongtai.view.DynamicRelayDetailViewImpl;
import com.beiing.tianshuai.tianshuai.entity.DynamicBean;
import com.beiing.tianshuai.tianshuai.entity.DynamicPraiseBean;
import com.beiing.tianshuai.tianshuai.entity.DynamicRelayDetailBean;
import com.beiing.tianshuai.tianshuai.entity.FollowBean;
import com.beiing.tianshuai.tianshuai.entity.UserInfoBean;
import com.beiing.tianshuai.tianshuai.fragment.EmotionCompleteFragment;
import com.beiing.tianshuai.tianshuai.mine.ui.LoginActivity;
import com.beiing.tianshuai.tianshuai.mine.ui.NewPersonalIndexActivity;
import com.beiing.tianshuai.tianshuai.util.DateUtil;
import com.beiing.tianshuai.tianshuai.util.DensityUtils;
import com.beiing.tianshuai.tianshuai.util.GlobalOnItemClickManagerUtils;
import com.beiing.tianshuai.tianshuai.util.SPUtils;
import com.beiing.tianshuai.tianshuai.util.SpanStringUtils;
import com.beiing.tianshuai.tianshuai.widget.ActionSheet;
import com.beiing.tianshuai.tianshuai.widget.ApproveListLayout;
import com.beiing.tianshuai.tianshuai.widget.CircleImageView;
import com.beiing.tianshuai.tianshuai.widget.CustomDialog;
import com.beiing.tianshuai.tianshuai.widget.CustomProgressDialog;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.lzy.ninegrid.ImageInfo;
import com.lzy.ninegrid.NineGridView;
import com.lzy.ninegrid.preview.NineGridViewClickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.tianshuai.easypopup.EasyPopup;
import com.tianshuai.easypopup.HorizontalGravity;
import com.tianshuai.easypopup.VerticalGravity;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by LZQ on 2017/8/17.
 */

public class DynamicRelayDetailActivity extends BaseActivity implements DynamicRelayDetailViewImpl, ActionSheet.OnSheetItemClickListener {

    @BindView(R.id.title_head)
    CircleImageView civTitleHead;
    @BindView(R.id.dynamic_detail_name)
    TextView tvName;
    @BindView(R.id.dynamic_detail_unit)
    TextView tvUnit;
    @BindView(R.id.dynamic_detail_attention)
    TextView tvAttention;
    @BindView(R.id.dynamic_detail_content_relay)
    TextView tvContentRelay;
    @BindView(R.id.dynamic_detail_from_name)
    TextView fromName;
    @BindView(R.id.dynamic_detail_content)
    TextView tvContent;
    @BindView(R.id.dynamic_detail_ninegridview)
    NineGridView mNinegridview;
    @BindView(R.id.dynamic_detail_time)
    TextView tvTime;
    @BindView(R.id.dynamic_detail_praise)
    TextView tvPraise;
    @BindView(R.id.dynamic_detail_comment)
    TextView tvComment;
    @BindView(R.id.dynamic_detail_forward)
    TextView tvForward;
    @BindView(R.id.dynamic_detail_comment_num)
    TextView mCommentNum;
    @BindView(R.id.dynamic_detail_recycler)
    RecyclerView mRecyclerView;
    @BindView(R.id.nstScrollView)
    NestedScrollView mScrollView;
    @BindView(R.id.dynamic_detail_edit)
    EditText mEditComment;
    @BindView(R.id.dynamic_detail_send)
    TextView mSend;
    @BindView(R.id.ll_former)
    LinearLayout mLlFormer;
    @BindView(R.id.avatars_container)
    LinearLayout avatarsContainer;
    @BindView(R.id.approve_list)
    ApproveListLayout approveList;
    @BindView(R.id.thing_num)
    TextView thingNum;
    @BindView(R.id.view_loading)
    View mLoadingBackground;
    @BindView(R.id.tv_add_one)
    TextView mTvAddOne;
    @BindView(R.id.iv_face)
    ImageView ivFace;
    @BindView(R.id.iv_keyboard)
    ImageView ivKeyBoard;
    @BindView(R.id.fl_emotionview_main)
    FrameLayout mEmotionLayout;
    @BindView(R.id.btn_order_by)
    ImageButton mBtnOrderBy;
    @BindView(R.id.smtRefreshLayout)
    SmartRefreshLayout mRefreshLayout;

    private DynamicBean.DataBean.DynamicsBean dynamicsBean;
    private List<DynamicRelayDetailBean.DataBean.CommentBean> commentBeanList;
    private List<DynamicRelayDetailBean.DataBean.UserThingBean> userThingBeanList;
    private DynamicRelayDetailBean.DataBean.UserThingBean mUserThingBean;
    private DynamicRelayDetailBean.DataBean dynamicRelayDetail;
    private DynamicRelayComment_RVAdapter mAdapter;
    private DynamicRelayDetailPresenter mPresenter;
    private String uid;                        //用户id
    private String dynamic_id;                 //动态id,唯一id
    private String to_uid;
    private String cid;                        //评论者id
    private String publisher_uid;              //动态发布者 uid
    private Drawable praise;
    private Drawable attention;
    private InputMethodManager imm;
    private Dialog bottomDialog;
    private int mPosition;
    private DynamicRelayDetailBean.DataBean.CommentBean mBean;
    private RequestOptions mAvatarOptions;
    private int dynamic_position;
    private AlphaAnimation mHideAnimation;
    private PopupMenu mPopupMenu;
    private EmotionCompleteFragment emotionCompleteFragment;
    private boolean emotionLayoutShow;      //表情面板是否显示
    private GlobalOnItemClickManagerUtils globalOnItemClickManager;
    private EasyPopup mPopup;               //评论列表排序菜单
    private int type = 0;                   //评论排序方式
    private int page = 1;                   //第几页
    private int num = 20;                    //每页有多少条数据
    private boolean isLoadMore;             //是否是上拉加载更多
    private List<String> approveUrlList;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_dynamic_detail_relay;
    }

    @Override
    protected void init() {
        CustomProgressDialog.showLoading(mContext, "", true);
        CustomProgressDialog.setCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                finish();
            }
        });
        initRecyclerView();
        initData();
        initPresenter();
        setListener();
        initEmotionMainFragment();
        initRefreshLayout();
        mPopup = new EasyPopup(mContext)
                .setContentView(R.layout.menu_dynamic_comment_order_by)
                .setAnimationStyle(R.style.QQPopAnim)
                .setFocusAndOutsideEnable(true)
                .createPopup();
    }

    private void initRefreshLayout() {
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                mPresenter.getRelayDetail(dynamic_id, uid, type, page, num, isLoadMore);
            }
        });

        mRefreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {

            }
        });
    }

    private void initEmotionMainFragment() {
        globalOnItemClickManager = GlobalOnItemClickManagerUtils.getInstance(mContext);
        globalOnItemClickManager.attachToEditText(mEditComment);
        emotionCompleteFragment = new EmotionCompleteFragment();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.add(R.id.fl_emotionview_main, emotionCompleteFragment);
        transaction.commit();
    }

    private void initPresenter() {
        mPresenter = new DynamicRelayDetailPresenter(this);
        mPresenter.getRelayDetail(dynamic_id, uid, type, page, num, isLoadMore);
    }


    private void initData() {
        Intent intent = this.getIntent();
        dynamicsBean = (DynamicBean.DataBean.DynamicsBean) intent.getSerializableExtra("dynamic");
        dynamic_id = intent.getStringExtra("dynamic_id");
        dynamic_position = intent.getIntExtra("dynamic_position", 0);

        /**********点击动态列表中评论按钮按钮过来时弹出输入框**********/
        if (intent.getStringExtra("comment") != null) {
            mEditComment.setFocusable(true);
            mEditComment.setFocusableInTouchMode(true);
            mEditComment.requestFocus();
        }

        uid = SPUtils.getString(this, "uid", "");

        praise = getResources().getDrawable(R.mipmap.praise_red_solid);
        attention = getResources().getDrawable(R.drawable.icon_add_32);

        imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);

        mAvatarOptions = new RequestOptions()
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .placeholder(R.mipmap.default_avatar)
                .centerCrop()
                .override(100, 100);

        mUserThingBean = new DynamicRelayDetailBean.DataBean.UserThingBean();
        mUserThingBean.setId(UserInfoBean.getUid(mContext));
        mUserThingBean.setName(UserInfoBean.getNickName(mContext));
        mUserThingBean.setPhoto(UserInfoBean.getAvatar(mContext));
    }

    @Override
    public void showDynamicRelayDetail(DynamicRelayDetailBean relayDetailBean) {
        dynamicRelayDetail = relayDetailBean.getData().get(0);
        if (null == relayDetailBean.getData().get(0).getUserThing()){
            userThingBeanList = new ArrayList<>();
        } else {
            userThingBeanList = relayDetailBean.getData().get(0).getUserThing();
        }
        approveUrlList = new ArrayList<>();
        if (userThingBeanList.size() > 0){
            for (int i = 0; i < userThingBeanList.size(); i++) {
                approveUrlList.add(userThingBeanList.get(i).getPhoto());
            }
            avatarsContainer.setVisibility(View.VISIBLE);
            thingNum.setText(userThingBeanList.size() > 13 ? "+" + String.valueOf(userThingBeanList.size()) + "人赞" : String.valueOf(userThingBeanList.size() + "人赞"));
        }
        approveList.updateApproveList(approveUrlList);
        Glide.with(getApplicationContext())
                .load((dynamicRelayDetail.getRphoto()).equals("") ? R.mipmap.default_avatar
                        : HttpRequestConstant.USER_PIC_HEAD + dynamicRelayDetail.getRphoto().toString())
                .into(civTitleHead);

        tvName.setText(dynamicRelayDetail.getRname());
        tvUnit.setText(dynamicRelayDetail.getU_unit());
        if (dynamicRelayDetail.getRcontent().equals("")) {
            tvContentRelay.setVisibility(View.GONE);
        } else {
            try {
                String rContentDecode = URLDecoder.decode(dynamicRelayDetail.getRcontent(), "UTF-8");
                tvContentRelay.setText(SpanStringUtils.getEmotionContent(mContext, tvContentRelay, rContentDecode));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        if ("".equals(dynamicRelayDetail.getContent())) {
            tvContent.setVisibility(View.GONE);
        } else {
            String decodeContent = null;
            try {
                decodeContent = URLDecoder.decode(dynamicRelayDetail.getContent(), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            tvContent.setText(SpanStringUtils.getEmotionContent(mContext, tvContent, decodeContent));
        }
        fromName.setText("@" + dynamicRelayDetail.getName());

        tvPraise.setText(String.valueOf(dynamicRelayDetail.getThing()));
        if (dynamicRelayDetail.getIs_thing() == 1) {
            praise.setBounds(0, 0, praise.getMinimumWidth(), praise.getMinimumHeight());
            tvPraise.setCompoundDrawables(praise, null, null, null);
        }
        tvComment.setText(dynamicRelayDetail.getComment_relay());
        tvForward.setText(dynamicRelayDetail.getRelay());
        tvTime.setText(DateUtil.timeStamp2Date(dynamicRelayDetail.getTime(),"MM-dd HH:mm"));

        mCommentNum.setText("评论" + dynamicRelayDetail.getComment_relay());

        List<DynamicRelayDetailBean.DataBean.PicnameBean> pic = dynamicRelayDetail.getPicname();
        if (pic != null && pic.size() > 0) {
            ArrayList<ImageInfo> imageInfos = new ArrayList<>();
            for (DynamicRelayDetailBean.DataBean.PicnameBean picBean : pic) {
                String url = HttpRequestConstant.DYNAMIC_PIC_HEAD + picBean.getPicname();
                ImageInfo imageInfo = new ImageInfo();
                imageInfo.setThumbnailUrl(url);
                imageInfo.setBigImageUrl(url);
                imageInfo.setImageViewHeight(Integer.parseInt(picBean.getHeight()));
                imageInfo.setImageViewWidth(Integer.parseInt(picBean.getWidth()));
                imageInfo.setImageHeight(Integer.parseInt(picBean.getHeight()));
                imageInfo.setImageWidth(Integer.parseInt(picBean.getWidth()));
                imageInfos.add(imageInfo);
            }
            mNinegridview.setAdapter(new NineGridViewClickAdapter(mContext, imageInfos));
        }

        to_uid = dynamicRelayDetail.getFormUid();
        publisher_uid = dynamicRelayDetail.getFormUid();
        mPresenter.isFollowed(uid, publisher_uid);
        if (dynamicRelayDetail.getFormUid().equals(uid)) {
            tvAttention.setVisibility(View.GONE);
        }
        tvComment.setText(dynamicRelayDetail.getComment().size() + "");

        List<DynamicRelayDetailBean.DataBean.CommentBean> commentBeen = dynamicRelayDetail.getComment();
        commentBeanList.clear();
        commentBeanList.addAll(commentBeen);
        mAdapter.notifyDataSetChanged();
        if (mRefreshLayout != null && (mRefreshLayout.isRefreshing() || mRefreshLayout.isLoading())){
            mRefreshLayout.finishRefresh();
            mRefreshLayout.finishLoadmore();
        }
    }

    private void initRecyclerView() {
        commentBeanList = new ArrayList<>();
        LinearLayoutManager manager = new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(manager);
        mRecyclerView.setNestedScrollingEnabled(false);
        mRecyclerView.getItemAnimator().setChangeDuration(0);
        mAdapter = new DynamicRelayComment_RVAdapter(mContext, commentBeanList);
        mRecyclerView.setAdapter(mAdapter);

        mAdapter.setOnItemViewClickListener(new DynamicRelayComment_RVAdapter.OnItemViewClickListener() {
            @Override
            public void onItemViewClick(View view, int position) {
                switch (view.getId()) {
                    case R.id.dynamic_comment_ll_head:
                        mAdapter.setOnItemClickListener(null);
                        Intent intent = new Intent(mContext, NewPersonalIndexActivity.class);
                        intent.putExtra("uid", commentBeanList.get(position).getUid());
                        startActivity(intent);
                        break;
//                    case R.id.dynamic_comment_more:
//                        mAdapter.setOnItemClickListener(null);
//                        cid = commentBeanList.get(position).getId();
//                        if (commentBeanList.get(position).getUid().equals(uid) && !TextUtils.isEmpty(UserInfoBean.getUid(mContext))) {
//                            showBottomDialog(position);
//                        }
//                        break;
                    case R.id.dynamic_comment_praise:
                        mAdapter.setOnItemClickListener(null);
                        if (TextUtils.isEmpty(UserInfoBean.getUid(mContext))) {
                            startActivity(new Intent(mContext, LoginActivity.class));
                        } else {
                            mPresenter.praiseComment(uid, commentBeanList.get(position).getId(), dynamicRelayDetail.getId(), commentBeanList.get(position).getUid(), dynamic_id, position);
                        }
                        break;
                    default:
                        mAdapter.setOnItemClickListener(new DynamicRelayComment_RVAdapter.OnItemClickListener() {
                            @Override
                            public void onItemClick(View view, int position) {
                                if (TextUtils.isEmpty(UserInfoBean.getUid(mContext))) {
                                    startActivity(new Intent(mContext, LoginActivity.class));
                                } else {
                                    if (commentBeanList.get(position).getUid().equals(UserInfoBean.getUid(mContext))){
                                        showPopupMenu(view, position, commentBeanList.get(position));
                                    } else {
                                        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                                        mEditComment.setFocusable(true);
                                        mEditComment.setFocusableInTouchMode(true);
                                        mEditComment.requestFocus();
                                        mEditComment.setHint("回复" + commentBeanList.get(position).getName());
                                        cid = commentBeanList.get(position).getId();
                                        to_uid = commentBeanList.get(position).getUid();
                                    }
                                }
                            }
                        });
                }
            }

            @Override
            public void onMoreClick(View view, int position, DynamicRelayDetailBean.DataBean.CommentBean bean) {
                cid = commentBeanList.get(position).getId();
                showBottomMenu(mContext, position, bean);
            }
        });

        mAdapter.setOnTextClickListener(new DynamicRelayComment_RVAdapter.OnTextClickListener() {
            @Override
            public void onTextClick(View view, final int position, final int itemposition, int textPosition) {
                switch (textPosition) {
                    case 1:
                        Intent intent = new Intent();
                        intent.setClass(mContext, NewPersonalIndexActivity.class);
                        intent.putExtra("uid", commentBeanList.get(position).getReply().get(itemposition).getFormUid());
                        mContext.startActivity(intent);
                        break;
                    case 2:
                        Intent intent1 = new Intent();
                        intent1.setClass(mContext, NewPersonalIndexActivity.class);
                        intent1.putExtra("uid", commentBeanList.get(position).getReply().get(itemposition).getToUid());
                        mContext.startActivity(intent1);
                        break;
//                    case 3:
//                        final AlertDialog.Builder confirmDialog = new AlertDialog.Builder(mContext);
//                        confirmDialog.setMessage("确定要删除这条回复么？");
//                        confirmDialog.setPositiveButton("确定", new DialogInterface.OnItemClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialogInterface, int i) {
//                                mPresenter.deleteReply(uid, commentBeanList.get(position).getReply().get(itemposition).getId(), position, itemposition);
//                            }
//                        });
//                        confirmDialog.setNegativeButton("取消", new DialogInterface.OnItemClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialogInterface, int i) {
//
//                            }
//                        });
//                        confirmDialog.show();
//                        break;
                    default:break;
                }
            }
        });

        mAdapter.setOnChildItemClickListener(new DynamicRelayComment_RVAdapter.OnChildItemClickListener() {
            @Override
            public void onChildItemClick(View view, int position, int childPosition) {
                Intent intent = new Intent();
                intent.setClass(mContext, CommentRelayReplyActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("reply", commentBeanList.get(position));
                intent.putExtra("position", position);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
    }

    private void showPopupMenu(View view, final int position, final DynamicRelayDetailBean.DataBean.CommentBean commentBean){
        mPopupMenu = new PopupMenu(mContext, view, Gravity.RIGHT);
        mPopupMenu.getMenuInflater().inflate(R.menu.comment_click_menu, mPopupMenu.getMenu());
        mPopupMenu.getMenu().findItem(R.id.item_copy).setVisible(false);
        mPopupMenu.show();
        mPopupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem menuItem) {
                switch (menuItem.getItemId()){
                    case R.id.item_delete:
                        mPresenter.deleteComment(uid, commentBean.getId(), dynamic_id, position, dynamic_position);
                        break;
                    default:break;

                }
                return false;
            }
        });
    }

    private void showBottomMenu(Context context, int position, DynamicRelayDetailBean.DataBean.CommentBean bean) {
        mPosition = position;
        mBean = bean;
        ActionSheet actionSheet = new ActionSheet(context);
        if (mBean.getUid().equals(uid)) {
            actionSheet.builder()
                    .setCancelable(true)
                    .setCanceledOnTouchOutside(true)
                    .addSheetItem("删除", ActionSheet.SheetItemColor.Blue, this)
                    .show();
        }
    }

    private void showBottomDialog(final int position) {
        bottomDialog = new Dialog(mContext, R.style.BottomDialog);
        View contentView = LayoutInflater.from(mContext).inflate(R.layout.dialog_my_dynamic, null);
        TextView delete = (TextView) contentView.findViewById(R.id.bottom_dialog_delete);
        TextView cancel = (TextView) contentView.findViewById(R.id.bottom_dialog_cancel);

        delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bottomDialog.dismiss();
                final AlertDialog.Builder confirmDialog = new AlertDialog.Builder(mContext);
                confirmDialog.setMessage("确定要删除这条回复么？");
                confirmDialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        mPresenter.deleteComment(uid, cid, dynamic_id, position, dynamic_position);
                    }
                });
                confirmDialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                });
                confirmDialog.show();
            }
        });

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bottomDialog.dismiss();
            }
        });

        if (!isFinishing()) {
            bottomDialog.show();
        }
        bottomDialog.setContentView(contentView);
        ViewGroup.LayoutParams layoutParams = contentView.getLayoutParams();
        layoutParams.width = getResources().getDisplayMetrics().widthPixels;
        contentView.setLayoutParams(layoutParams);

        bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);

        bottomDialog.setCanceledOnTouchOutside(true);
    }

    @OnClick({R.id.title_iv_back, R.id.dynamic_detail_attention, R.id.dynamic_detail_from_name,
            R.id.dynamic_detail_praise, R.id.dynamic_detail_comment, R.id.dynamic_detail_forward,
            R.id.dynamic_detail_send, R.id.ll_former})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_iv_back:
                finish();
                break;
            case R.id.dynamic_detail_attention:
                if (TextUtils.isEmpty(UserInfoBean.getUid(mContext))) {
                    startActivity(new Intent(mContext, LoginActivity.class));
                } else {
                    //关注用户
                    mPresenter.setFollowed(uid, publisher_uid);
                }
                break;
            case R.id.ll_former:
                Intent former_intent = new Intent();
                former_intent.setClass(mContext, DynamicDetailActivity.class);
                former_intent.putExtra("dynamic_id", dynamicRelayDetail.getId());
                startActivity(former_intent);
                break;
            case R.id.dynamic_detail_from_name:
                Intent intent = new Intent(mContext, NewPersonalIndexActivity.class);
                intent.putExtra("uid", dynamicRelayDetail.getUid());
                startActivity(intent);
                break;
            case R.id.dynamic_detail_praise:
                if (TextUtils.isEmpty(UserInfoBean.getUid(mContext))) {
                    startActivity(new Intent(mContext, LoginActivity.class));
                } else {
                    mPresenter.addPraise(uid, dynamic_id, dynamicRelayDetail.getId(), publisher_uid, dynamic_position);
                }
                break;
            case R.id.dynamic_detail_comment:
                if (TextUtils.isEmpty(UserInfoBean.getUid(mContext))) {
                    startActivity(new Intent(mContext, LoginActivity.class));
                } else {
                    imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                    mEditComment.setFocusable(true);
                    mEditComment.setFocusableInTouchMode(true);
                    mEditComment.requestFocus();
                }
                break;
            case R.id.dynamic_detail_forward:                   //转发原动态
                if (TextUtils.isEmpty(UserInfoBean.getUid(mContext))) {
                    startActivity(new Intent(mContext, LoginActivity.class));
                } else {
                    Intent forward_intent = new Intent();
                    forward_intent.setClass(mContext, DynamicForwardActivity.class);
                    Bundle forward_bundle = new Bundle();
                    forward_bundle.putSerializable("dynamic", dynamicsBean);
                    forward_intent.putExtras(forward_bundle);
                    startActivity(forward_intent);
                }
                break;
            case R.id.dynamic_detail_send:
                if (TextUtils.isEmpty(mEditComment.getText()) || "".equals(mEditComment.getText().toString().trim())) {
                    //不做处理
                } else {
                    if (mEditComment.getHint().equals("说几句...")) {      //评论
                        String content = mEditComment.getText().toString().trim();
                        String contentUTF8 = null;
                        try {
                            contentUTF8 = URLEncoder.encode(content, "UTF-8");
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        mPresenter.addComment(dynamic_id, uid, dynamicRelayDetail.getId(), to_uid, contentUTF8, dynamic_position);
                        if (imm != null) {
                            imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
                        }
                        mEditComment.clearFocus();
                        mEditComment.setText("");
                    } else {                                             //回复
                        String content = mEditComment.getText().toString().trim();
                        String contentUTF8 = null;
                        try {
                            contentUTF8 = URLEncoder.encode(content, "UTF-8");
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        mPresenter.addReply(dynamic_id, cid, uid, to_uid, contentUTF8, to_uid);
                        imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
                        mEmotionLayout.setVisibility(View.GONE);
                        mEditComment.clearFocus();
                        mEditComment.setText("");
                    }
                }
                break;
            default:break;

        }
    }

    private void setListener() {
        CustomProgressDialog.setListener(new CustomProgressDialog.OnDismiss() {
            @Override
            public void onDismissListener() {
                setHideAnimation(mLoadingBackground, 888);
            }
        });

        mScrollView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                mEditComment.setFocusable(false);
                mEditComment.setHint("说几句...");
                imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
                mEmotionLayout.setVisibility(View.GONE);
                return false;
            }
        });


        mEditComment.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (TextUtils.isEmpty(UserInfoBean.getUid(mContext))) {
                    startActivity(new Intent(mContext, LoginActivity.class));
                } else {
                    mEditComment.setFocusable(true);
                    mEditComment.setFocusableInTouchMode(true);
                    mEditComment.requestFocus();
                    mEmotionLayout.setVisibility(View.GONE);
                    emotionLayoutShow = false;
                }
                return false;

            }
        });

        mSend.setClickable(false);
        mEditComment.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0 && !"".equals(s.toString().trim())) {     //有文字内容
                    mSend.setBackgroundResource(R.drawable.publish_blue);
                    mSend.setClickable(true);
                } else {
                    mSend.setBackgroundResource(R.drawable.publish_gray);    //没有文字内容
                    mSend.setClickable(false);
                }
            }
        });
        civTitleHead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mContext, NewPersonalIndexActivity.class);
                intent.putExtra("uid", dynamicRelayDetail.getFormUid());
                startActivity(intent);
            }
        });

        avatarsContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mContext, PraiseDetailActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("dynamicDetail", dynamicRelayDetail);
                intent.putExtra("from_activity", "dynamic_relay");
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });

        // 点赞头像的点击事件
        approveList.setOnHeaderClickListener(new ApproveListLayout.OnHeaderClickListener() {
            @Override
            public void onHeaderClick(View view, int position) {

            }
        });

        ivFace.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ivFace.setVisibility(View.GONE);
                ivKeyBoard.setVisibility(View.VISIBLE);
                emotionLayoutShow = true;
                imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
                mEmotionLayout.setVisibility(View.VISIBLE);
            }
        });

        ivKeyBoard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mEmotionLayout.setVisibility(View.GONE);
                ivKeyBoard.setVisibility(View.GONE);
                ivFace.setVisibility(View.VISIBLE);
                emotionLayoutShow = false;
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                mEditComment.setFocusable(true);
                mEditComment.setFocusableInTouchMode(true);
                mEditComment.requestFocus();
            }
        });

        mBtnOrderBy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initPopupWindow();
                int i = v.getLayoutParams().width / 2 + DensityUtils.dp2px(mContext, 6);
                mPopup.showAtAnchorView(v, VerticalGravity.BELOW, HorizontalGravity.ALIGN_RIGHT, i, -DensityUtils.dp2px(mContext, 9));
            }
        });
    }

    private void initPopupWindow(){
        //最热
        TextView tvOrderByHot = mPopup.getView(R.id.action_order_by_hot);
        //最新
        TextView tvOrderByNew = mPopup.getView(R.id.action_order_by_new);
        //最先
        TextView tvOrderByOld = mPopup.getView(R.id.action_order_by_old);

        tvOrderByHot.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                type = 2;
                mPresenter.getRelayDetail(dynamic_id, uid, type, page, num, isLoadMore);
                mPopup.dismiss();
            }
        });

        tvOrderByNew.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                type = 0;
                mPresenter.getRelayDetail(dynamic_id, uid, type, page, num, isLoadMore);
                mPopup.dismiss();
            }
        });

        tvOrderByOld.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                type = 1;
                mPresenter.getRelayDetail(dynamic_id, uid, type, page, num, isLoadMore);
                mPopup.dismiss();
            }
        });
    }


    private void setHideAnimation(final View view, int duration) {
        if (null == view || duration < 0) {
            return;
        }
        if (null != mHideAnimation) {
            mHideAnimation.cancel();
        }

        mHideAnimation = new AlphaAnimation(1.0f, 0.0f);
        mHideAnimation.setDuration(duration);
        mHideAnimation.setFillAfter(true);
        mHideAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                view.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        view.startAnimation(mHideAnimation);
    }

    @Override
    public void refreshComment() {
        mAdapter.notifyDataSetChanged();
    }

    // 显示点赞结果
    @Override
    public void showPraiseResult(DynamicPraiseBean praiseBean) {
        String count = String.valueOf(praiseBean.getData().getCount());
        if (praiseBean.getCode() == 200) {
            LikeAnimator.thumbAnimator(mContext, tvPraise);
            LikeAnimator.addOneTextAnimator(mContext, mTvAddOne);
            tvPraise.setText(count);
            if (null != mUserThingBean){
                userThingBeanList.add(0, mUserThingBean);
            }

            approveUrlList.add(0, UserInfoBean.getAvatar(mContext));
            approveList.updateApproveList(approveUrlList);
            thingNum.setText(userThingBeanList.size() > 13 ? "+" + String.valueOf(userThingBeanList.size()) + "人赞" : String.valueOf(userThingBeanList.size() + "人赞"));
        } else if (praiseBean.getCode() == 201) {
            LikeAnimator.disLikeAnimator(mContext, tvPraise);
            tvPraise.setText(count);
            DynamicRelayDetailBean.DataBean.UserThingBean userThingBeanDel = new DynamicRelayDetailBean.DataBean.UserThingBean();
            for (DynamicRelayDetailBean.DataBean.UserThingBean userThingBean : userThingBeanList) {
                if (TextUtils.equals(userThingBean.getId(), UserInfoBean.getUid(mContext))) {
                    userThingBeanDel = userThingBean;
                }
            }
            userThingBeanList.remove(userThingBeanDel);
            String deleteUrl = null;
            for (String url : approveUrlList){
                if (TextUtils.equals(url, UserInfoBean.getAvatar(mContext))){
                    deleteUrl = url;
                }
            }
            approveUrlList.remove(deleteUrl);
            if (approveUrlList.size() == 0){
                avatarsContainer.setVisibility(View.GONE);
            }
            approveList.updateApproveList(approveUrlList);
            thingNum.setText(userThingBeanList.size() > 13 ? "+" + String.valueOf(userThingBeanList.size()) + "人赞" : String.valueOf(userThingBeanList.size() + "人赞"));
        }
    }

    @Override
    public void deleteComment(int position) {
        mAdapter.removeItem(position);
        mAdapter.notifyItemRemoved(position);
    }

    @Override
    public void deleteReply(int position, int childPosition) {
//        mAdapter.removeChild(position, childPosition);
    }

    @Override
    public void showError(int errorType) {
        switch (errorType) {
            case 0:         //获取详情数据错误
                showShortText("加载数据失败");
                break;
            case 1:
                showShortText("评论失败");
                break;
            case 2:
                showShortText("回复失败");
                break;
            case 3:
                showShortText("点赞失败");
                break;
            case 4:
                showShortText("评论删除失败");
                break;
            case 5:
                showShortText("删除回复失败");
                break;
            default:break;

        }
    }

    @Override
    public void showProgress() {
        CustomProgressDialog.showLoading(mContext, "请稍后，正在努力加载...", true);
    }

    @Override
    public void hideProgress() {
        CustomProgressDialog.stopLoading();
    }

    @Override
    public void showCommentPraiseResult(DynamicPraiseBean praiseBean, int comment_position) {
        commentBeanList.get(comment_position).setThing(praiseBean.getData().getCount() + "");
        if (praiseBean.getCode() == 200) {
            commentBeanList.get(comment_position).setIs_thing(1);
        } else if (praiseBean.getCode() == 201) {
            commentBeanList.get(comment_position).setIs_thing(0);
        }
        mAdapter.notifyItemChanged(comment_position);
    }

    // 该动态已不存在
    @Override
    public void showDynamicNotExist() {
        showShortText("该动态已被作者删除");
        finish();
    }

    @Override
    public void showFollowed(FollowBean followBean) {
        if (followBean.getCode() == 0) {             //未关注
            tvAttention.setText("关注");
            tvAttention.setCompoundDrawablesWithIntrinsicBounds(attention, null, null, null);
        } else if (followBean.getCode() == 1) {      //已关注
            tvAttention.setText("已关注");
            tvAttention.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
        }
    }

    /**
     * 底部弹出框的点击事件
     *
     * @param which
     */
    @Override
    public void onClick(int which) {
        switch (which) {
            case 1:
                CustomDialog dialog = new CustomDialog(mContext, R.style.dialog,
                        "确定要删除这条评论么？",
                        new CustomDialog.OnCloseListener() {
                            @Override
                            public void onClick(Dialog dialog, boolean confirm) {
                                if (confirm){
                                    mPresenter.deleteComment(uid, cid, dynamic_id, mPosition, dynamic_position);
                                    dialog.dismiss();
                                } else {
                                    dialog.dismiss();
                                }
                            }
                        }).setTitle("提示");
                dialog.setCanceledOnTouchOutside(true);
                dialog.show();
//                AlertDialog.Builder confirmDialog = new AlertDialog.Builder(mContext);
//                confirmDialog.setMessage("确定要删除这条回复么？");
//                confirmDialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialogInterface, int i) {
//                        mPresenter.deleteComment(uid, cid, dynamic_id, mPosition, dynamic_position);
//                    }
//                });
//                confirmDialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialogInterface, int i) {
//
//                    }
//                });
//                confirmDialog.show();
                break;
            default:break;

        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        initEmotionMainFragment();
    }
}
